package demo1;

import java.time.LocalDate;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-11
 * Time: 14:38
 */
public class TestDemo2 {

    public static void main(String[] args) {
        //创建固定线程池数量
        ExecutorService erService = Executors.newFixedThreadPool(10);
        for(int i =0;i<10;++i){
            erService.submit(new TimerTask() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }

    //submit可以执行有返回值的和无返回值的
    public static void main2(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(10);
       Future<Integer> futureTask = service.submit(new Callable<Integer>(){
           @Override
           public Integer call(){
               int sum =0;
               for(int i =0;i<100;++i){
                   sum+=i;
               }
               return sum;
           }
       });
       //返回任务结果
        System.out.println(futureTask.get());

    }

    public static void main3(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        //自定义线程池--->动态增长的线程池--会根据任务的数量,创建线程数量,一定时间内可以重复使用某线程
        for(int i =0;i<10;++i){
            int finalSz  = i;
            service.submit(()->{
                System.out.println("第" + finalSz + "次" + "线程名"+ Thread.currentThread().getName());
            });
        }
    }

    public static void main7(String[] args) {
        //执行定时任务的线程池
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);//5个线程
        System.out.println("添加任务时间" + LocalDate.now());

        executor.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行子任务"+ LocalDate.now());
            }
        },2,TimeUnit.SECONDS);

    }

    public static void main6(String[] args) {
        //执行单线程任务线程池
        ExecutorService executor = Executors.newSingleThreadExecutor();
        for(int i =0;i<10;++i){
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程名"+Thread.currentThread().getName());
                }
            });
        }
    }







}
